<?php
//include './core/rongyun.php';
class UserAction extends Action{
	
	public function index(){
		echo 'index';
	}



//短信发送功能
	public function sendSms($phone,$data){
		$post_data = array();
		$post_data['userid'] = C("__ACCOUNT__");//iconv('GB2312', 'GB2312',"询问对接人");
		$post_data['password'] = C("__PSWD__");//iconv('GB2312', 'GB2312',"询问对接人");
		$post_data['destnumbers'] =$phone;
		$post_data["sendtime"]="";//sendtime参数格式为 YYYY-MM-DD HH:MM:SS 如:2008-05-12 10:00:00
		$post_data['msg']=mb_convert_encoding("$data",'UTF-8', 'auto');
		$url='http://211.147.244.114:9801/CASServer/SmsAPI/SendMessage.jsp';
		//构成请求url地址
	
		$o="";
		foreach ($post_data as $k=>$v)
		{
			$o.= "$k=".urlencode($v)."&";
		}
		$post_data=substr($o,0,-1);
		//curl会话
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//设置只将数据返回，不自动输出任何数据
		$result =curl_exec($ch);
		curl_close ( $ch );
		//分解返回值
		$arr = explode(" ", $result);
		$var = array();
		for($i = 1;$i<count($arr);$i++){
			$res = explode("=", $arr[$i]);
			$var[$res[0]] = trim($res[1],"\"");
		}
	
		$sms= M("Smssubscribe");
		$sms->phone = $phone;
		$sms->secret = $data;
		$sms->create_time = time();
		$sms->enable = $var['return'];
		$sms->msgid = $var["msgid"];
		$sms->add();
		if(!$var['return']){
			$value = ["code" => "success"];
			header("Content-Type: text/json");
			die(et($value));
		}else{
			$value = ["code" => "wrong"];
			header("Content-Type: text/json");
			die(et($value));
		}
	}
	
//短信验证码
	public function sendCode(){
		
		//获取前台输入的手机号码
		$uid = dt($_REQUEST['uid']);
		$phone=dt($_REQUEST['phone']);
		$this->testPhone($uid,$phone,dt($_REQUEST["type"]));
		$code = $this->code();
		$data="您好！验证码是：$code";
		//2.发送短信
		$this->sendSms($phone, $data);
	}
//检查电话是否符合资格	
//type {register,forgetPW}
	public function testPhone($uid,$phone,$type){
		$user=D("User");
		$users=$user->where("phone = $phone")->find();
		if($type == "bind"){
			if($users){
				//有数据
				//则电话已经被使用了，不能重复绑定
				$value = ["code" =>"already"];
				header("Content-Type: text/json");
				die(et($value));
			}
		}elseif ($type == "other"){
			if(!$user->where("phone = $phone and uid = $uid")->find()){
				//没有数据
				//则电话未被绑定，不能获取验证码
				$value = ["code" =>"nobind"];
				header("Content-Type: text/json");
				die(et($value));
			}
		}
		
		
	}
	//生成验证码
	public function code(){
		$code = rand(100000,999999);
		$data = $code ;
		$_SESSION['code'] = $code;
		return $data;
	}
	//生成token
	public function getToken(){
			$str1 = range(0,9);
			$str2 = range("a","z");
			$str3 = range("A","Z");
			$str = array_merge($str1,$str2,$str3);
			$token = '';
			for($i=0;$i<32;$i++){
				$var = array_rand($str,1);
				$token=$token.$str[$var];
			}
			return $token;
	}
	
	//注册
	public function register(){//【注册】
		$sex = dt($_REQUEST['sex']);
		$uname = t(dt($_REQUEST['uname']));
		
		//电话 验证码 密码不能为空
		if (empty( $uname ) )
		{
			$value = ["code" =>"empty"];
			header("Content-Type: text/json");
			die(et($value));
		}
		
		//检验用户是否已经注册
		$user=M("User");
		$find=$user->where("uname='$uname'")->find();
	
		if($find){
			//有数据
			//则用户名已经注册过来了，不能重复注册
			$value = ["code" =>"already"];
			header("Content-Type: text/json");
			die(et($value));
		}
			//$sex = 1 == dt($_REQUEST['sex']) ? 1 : 2;//1男2女
			$password = trim(dt($_REQUEST['password']));
			$repassword = trim(dt($_REQUEST['repassword']));
			
			//检查密码
			if(!model("Register")->isValidPassword($password, $repassword)){
				$value = ["code" =>"pwfalse","massage"=>model("Register")->getLastError()];
				header("Content-Type: text/json");
				die(et($value));
			}
			
			$token = $this->getToken();
			//dump($token);exit;
			$token_expired = strtotime("1 month");
			$login_salt = rand(11111, 99999);
			$map['uname'] = $uname;
			//$map['sex'] = $sex;
			$map['login_salt'] = $login_salt;
			$map['password'] = md5(md5($password).$login_salt);
			//$map['phone'] = $phone;
			$map['regip'] = get_client_ip();
			$map['ctime'] = time();
			$map['is_audit'] = 1;//是否通过审核
			$map['is_active'] =  1;//是否激活
			$map['is_init'] =  1;//是否初始化
			$map['first_letter'] = getFirstLetter($uname);
			$map['token'] = $token;
			$map['token_expired'] = $token_expired;
			$map['master_code'] = rand(100,999).str_replace("==", "", base64_encode(time()));
			if ( preg_match('/[\x7f-\xff]+/', $map['uname'] ) ){
				//昵称和呢称拼音保存到搜索字段
				$map['search_key'] = $map['uname'].' '.model('PinYin')->Pinyin( $map['uname'] );
			} else {
				$map['search_key'] = $map['uname'];
			}
			
			if(model('User')->add($map)){
				$users=$user->where("uname='$uname'")->find();
				$this->setUserGroud($users["uid"]);
				
				$value = ["code" =>"success","data"=>$users];
				header("Content-Type: text/json");
				die(et($value));
			}else{
				$value = ["code" =>"wrong"];
				header("Content-Type: text/json");
				die(et($value));
				
			}
			
		

	}
	//将客户端注册的用户设置为正常用户组
	public function setUserGroud($id){
		$group = M("User_group_link");
		$group->uid=$id;
		$group->user_group_id = 3;
		$group->add();
	}
	
//	public function checkToken(){//【token验证】
//		$uid = dt($_REQUEST['uid'];
//		$token = dt($_REQUEST['token'];
//		$user = M('User');
//		$find = $user->where("uid = '$uid' and token = '$token'")->find();
//		if(!$find){//token或uid不正确
//			$value = ["code" =>"false"];
//			header("Content-Type: text/json");
//			die(et($value));
//		}else{
//			$time = time();
//			$token_expired = $find['token_expired'];
//			if($time>$token_expired){//token过期
//				$value = ["code" =>"tokenfalse"];
//				header("Content-Type: text/json");
//				die(et($value));
//			}else{
//				$value = ["code" =>"success",'data'=>$find];
//				header("Content-Type: text/json");
//				die(et($value));
//			
//			}
//		}
//	
//	}
	
	public function login(){//【登录】
	
		$uname = dt($_REQUEST["uname"]);
		$password = dt($_REQUEST["password"]);
		if (empty($uname) || empty($password)){
			$value = ["code" =>"empty"];
			header("Content-Type: text/json");
			die(et($value));
		}
		
		$u=M("User");
		$users=$u->where("uname = '$uname'")->find();
		
		if($users){
				//有数据,获取login_salt
			$login_salt=$users["login_salt"];	
				
		}else {
			$value = ["code" =>"noregister"];
			header("Content-Type: text/json");
			die(et($value));
		}
		
		$password = md5(md5($password).$login_salt);
		
		if ($password == $users["password"]){
			$u->uid = $uid = $users['uid'];
			$u->token = $this->getToken();
			$u->token_expired = strtotime("1 month");
			$u->save();
			$user_info = $u->where("uid = $uid")->find();
			if($user_info['avatar']){
				$user_info['avatar'] = SITE_URL.'/'.$user_info['avatar'];
			}
			
			$value = ["code" =>"success","user"=>$user_info];
			header("Content-Type: text/json");
			die(et($value));
		}else{
			$value = ["code" =>"wrong"];
			header("Content-Type: text/json");
			die(et($value));
		}
	}
	
	
	//更新用户信息
	/*
	 * 头像
	 * 昵称
	 * 手机 不可改
	 * 邮箱
	 * 性别 sex
	 * 地址*/
	public function updateUser(){//【更新个人信息】
	
		$user = M("User");
		$id=dt($_REQUEST['uid']);

		if(dt($_REQUEST['email'])!=null){
			$email = dt($_REQUEST["email"]);
			if($user->where("email = '$email'")->find()){
				$value = ["code" =>"emailfalse"];
				header("Content-Type: text/json");
				die(et($value));
			}
			$user->email = dt($_REQUEST["email"]);
		}

		if(dt($_REQUEST['sex'])!=null){
		
			$user->sex = dt($_REQUEST["sex"]);
		}
		if(dt($_REQUEST['location'])!=null){
		
			$user->location = dt($_REQUEST["location"]);
		}
		
		if(isset($_FILES["avatar"])){
			if($_FILES['avatar']['error'] == 0){
				
				$upload= new UploadFile();
				$upload->autoSub=true; //开启子目录保存文件
				$upload->maxSize = 2097152;//最大为2m
				$upload->subName=array('date','Y-m-d');//以时间格式生成文件夹
				$upload->exts=array('jpg','jpeg','gif','png','bmp');//可上传的类型
				$upload->savePath='data/user/avatar/';
				$info=$upload->upload();
				
					
				if(!$info){
					$this->error($upload->getError(),'add',3);
				}
				$avatarinfo = $upload->getUploadFileInfo();
				//dump($avatarinfo);exit;
				$user->avatar=$avatarinfo['0']['savepath'].$avatarinfo['0']['savename'];
				
			}
		}
		
		if($user->where("uid = $id")->save()){
			$users=$user->where("uid = $id")->find();
			if($users['avatar']){
				$users['avatar'] = SITE_URL.'/'.$users['avatar'];
			}
			$value = ["code" =>"success","data"=>$users];
			header("Content-Type: text/json");
			die(et($value));
		}else{
			$value = ["code" =>"wrong"];
			header("Content-Type: text/json");
			die(et($value));
		}
	
	}
	
	public function bindPhone(){//【绑定手机和设置交易密码】
		$phone = dt($_REQUEST['phone']);
		$code = dt($_REQUEST['code']);
		$uid = dt($_REQUEST['uid']);
		$fpassword = dt($_REQUEST['fpassword']);
		$refpassword = dt($_REQUEST['refpassword']);
		$user = M('User');
		if(empty($phone) || empty($code) || empty($fpassword) || empty($refpassword)){
			$value = ["code" =>"empty"];
			header("Content-Type: text/json");
			die(et($value));
		}
			//检查密码
			if(!model("Register")->isValidPassword($fpassword, $refpassword)){
				$value = ["code" =>"pwfalse","massage"=>model("Register")->getLastError()];
				header("Content-Type: text/json");
				die(et($value));
			}
			$login = $user->where("uid = $uid")->find();
			$md5f = md5(md5($fpassword).$login['login_salt']);
			//echo $md5f;exit;
			if($md5f == $login['password']){
				$value = ["code" =>"ispassword"];
				header("Content-Type: text/json");
				die(et($value));
			
			}
			
			$find=$user->where("uid = $uid")->field("phone")->find();
			if($find['phone']!=null || !empty($find['phone'])){
				$value = ["code" =>"binded"];
				header("Content-Type: text/json");
				die(et($value));
			}
			if ($code!=$_SESSION['code'])
			{
// 				$value = ["code" =>"false"];
// 				header("Content-Type: text/json");
// 				die(et($value));
			}
			$user->fpassword = $md5f;
			$user->phone = dt($_REQUEST["phone"]);
			//dump($user);exit;
			if($user->where("uid = $uid")->save()){
				$value = ["code" =>"success"];
				header("Content-Type: text/json");
				die(et($value));
			}else{
				$value = ["code" =>"false"];
				header("Content-Type: text/json");
				die(et($value));
			}
	
	}
	
//	public function changeFpaddword(){//【修改交易密码】
//		$uid = dt($_REQUEST['uid']);
//		$code = dt($_REQUEST['code']);
//		$newfpwd = dt($_REQUEST['newfpwd']);
//		$renewfpwd = dt($_REQUEST['renewfpwd']);
//		
//	
//	}
	
	public function uploadImage(){//【上传动态附带图片】
	
		$upload	= new UploadFile();
	
		$upload= new UploadFile();
		$upload->autoSub=true; //开启子目录保存文件
		$upload->maxSize = 2097152;//最大为2m
		$upload->exts=array('jpg','jpeg','gif','png','bmp');//可上传的类型
		$upload->savePath='data/upload/user/avatar/';
	
		$info = $upload->upload();
	
		if($info){
			$result= $upload->getUploadFileInfo();
	
		}else{
	
			return  false;
		}
	
	
		return $result;
	
	}
	
	//忘记密码
	public function forgetPassword(){//【忘记密码】
		$phone = dt($_REQUEST["phone"]);
		$code = dt($_REQUEST['code']);
		$password = dt($_REQUEST["password"]);
		$repassword = dt($_REQUEST["repassword"]);
		//判断是否有空值
		if ( empty( $phone )  || empty( $code ) )
		{
			$value = ["code" =>"empty"];
			header("Content-Type: text/json");
			die(et($value));
		}
		//判断短信验证码是否正确
		if ($code!=$_SESSION['code'])
		{
// 			$value = ["code" =>"false"];
// 			header("Content-Type: text/json");
// 			die(et($value));
		}
		//判断密码正确性
		if(!model("Register")->isValidPassword($password, $repassword)){
			
			$value = ["code" =>"false","massage"=>model("Register")->getLastError()];
			header("Content-Type: text/json");
			die(et($value));
		}
		
		$user=D("User");
		$users=$user->where("phone = $phone")->find();
		
		if($users){
			//有数据
			//则电话已经注册过来了，可以获取
			$login_salt=$users["login_salt"];
		}else{
			//没有数据，则不能修改
			$value = ["code" =>"nobinded"];
			header("Content-Type: text/json");
			die(et($value));
		}
		
		$user->password = md5(md5($password).$login_salt);
		if ($user->where("phone = $phone")->save()){
			$value = ["code" =>"success"];
			header("Content-Type: text/json");
			die(et($value));
		}else{
			$value = ["login" =>"wrong"];
			header("Content-Type: text/json");
			die(et($value));
		}
		
	}
	//修改密码

	public function changePassword() {//【修改密码】
		$password = t(dt($_REQUEST['password']));
		$repassword = t(dt($_REQUEST['repassword']));
		// 验证信息
		if($password != $repassword) {
			// 新密码与确认密码不一致
			$value = ["code" =>"wrong","massage"=>"新密码与确认密码不一致"];
			header("Content-Type: text/json");
			die(et($value));
		}
		if(strlen($password) < 6) {
// 			$this->error('密码太短了，最少6位');
			$value = ["code" =>"wrong","massage"=>'密码太短了，最少6位'];
			header("Content-Type: text/json");
			die(et($value));
		}
		if(strlen($password) > 15) {
// 			$this->error('密码太长了，最多15位');
			$value = ["code" =>"wrong","massage"=>'密码太长了，最多15位'];
			header("Content-Type: text/json");
			die(et($value));
		}
		if($password == dt($_REQUEST['oldpassword'])) {
			// 新密码与旧密码相同
			$value = ["code" =>"wrong","massage"=>"新密码与旧密码相同"];
			header("Content-Type: text/json");
			die(et($value));			
		}
	
		$user_model = model('User');
		$uid=dt($_REQUEST["uid"]);
		$map['uid'] = dt($_REQUEST["uid"]);
		$user_info = $user_model->where($map)->find();
		if($user_info['password'] == $user_model->encryptPassword(dt($_REQUEST['oldpassword']), $user_info['login_salt'])) {
			$data['login_salt'] = rand(11111, 99999);
			$data['password'] = $user_model->encryptPassword($password, $data['login_salt']);
			$res = $user_model->where("`uid` = $uid")->save($data);
			$info = $res ? L('PUBLIC_PASSWORD_MODIFY_SUCCESS') : L('PUBLIC_PASSWORD_MODIFY_FAIL');			// 密码修改成功，密码修改失败
		} else {
			$info = L('PUBLIC_ORIGINAL_PASSWORD_ERROR');			// 原始密码错误
		}
		$res = $res?"success":"wrong";
		$value = ["code" =>$res,"massage"=>$info];
		header("Content-Type: text/json");
		die(et($value));
	}
	
	public function testUname($name){
		if (M("User")->where("uname = '$name'")->find()){
			return false;
		}else{
			return true;
		}
	
	}
	
	public function getUser(){//【获取用户信息】
		$uid = dt($_REQUEST["uid"]);
		$data = M("User")->where("uid = $uid")->field("uid,password,phone,uname,is_active,is_del,email,location,avatar,master_id,master_code,token,token_expired,avatar,fpassword")->find();
		if($data == false){
			$value = ["code" =>"wrong","massage"=>M("User")->getDbError()];
			header("Content-Type: text/json");
			die(et($value));
		}else{
			if($data['avatar']){
				$data['avatar'] = SITE_URL.'/'.$data['avatar'];
			}
			$value = ["code" =>"success","data"=>$data];
			header("Content-Type: text/json");
			die(et($value));
		}
	}
	
	public function checkFpassword(){//【检查用户是否设置了交易密码】
		$uid = dt($_REQUEST["uid"]);
		$data = M("User")->where("uid = $uid")->field("fpassword")->find();
		if(!$data['fpassword']){
			$value = ["code" =>"notfound"];
			header("Content-Type: text/json");
			die(et($value));
		}else{
			$value = ["code" =>"success"];
			header("Content-Type: text/json");
			die(et($value));
		}
	}
	
	public function UserGroup($uid,$type="add"){
		$group_link = M("User_group_link");
	
		if($type == "add"){
			//添加教练资格
			$group_link->uid = $uid;
			$group_link->user_group_id = 3;
			if($group_link->add()){
				return true;
			}
		}elseif ($type == "dele"){
			//去除教练资格
			if($group_link->where("uid = $uid and user_group_id = 3")->delete()){
				return true;
			}
				
		}
		return false;
	
	}
	

}